﻿using System;
using ZFine.Application.Gas;
using ZFine.Application.SystemManage;
using ZFine.Code;
using ZFine.Domain.Entity.Gas;
using ZFine.Domain.Entity.SystemManage;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;

namespace ZFine.Web.Areas.Gas.Controllers
{
    public class ResidentController : ControllerBase
    {
        private ResidentApp residentApp = new ResidentApp();
        private FaceRecordApp faceRecordApp = new FaceRecordApp();
        [HttpGet]
        [HandlerAuthorize(ignore:false)]
        public override ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Form()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Details()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult Update()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult Upload()
        {
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, ResidentEntity in_resident, string StartDate, String EndDate)
        {
            List<ResidentEntity> l_resident = residentApp.GetList(pagination, in_resident.RName,in_resident.IDNumber, StartDate, EndDate);
            var l_diningCount = (from dingCount in faceRecordApp.GetList("").Where(a=>a.Result== ZFine.Application.Enum.Gas.FaceRecordResult.已刷卡.ToString())
                                 group dingCount by dingCount.IDNumber into s
                                  select (new { IDNumner = s.Key, count= s.Count()})).ToList();
            //因为有部分人员没有就餐记录，需要使用左连接
            var rows = from _resident in l_resident
                       join _diningCount in l_diningCount on _resident.IDNumber equals _diningCount.IDNumner into merge
                       from m in merge.DefaultIfEmpty()
                       select new
                       {
                           F_Id = _resident.F_Id,
                           RName = _resident.RName,
                           IDNumber = _resident.IDNumber,
                           Sex = _resident.sex,
                           Telephone = _resident.telephone,
                           Telephone2 = _resident.telephone2,
                           Address = _resident.address,
                           CardType = _resident.CardType,
                           DiningRecordCount = m?.count.ToString()??"0",
                           FaceRecognizeTime=_resident.FaceRecognizeTime.ToString(PubClass.TimeFormat)
                       };
            var data = new
            {
                page = pagination.page,//当前页  1  2 3 之类
                records = pagination.records,//总条数  这里应该是18
                rows = rows,//分页的数据
                total = pagination.total,//页数
            };
            return Content(data.ToJson());
        }
        //修改页数据
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJsonForUpdate(string keyValue)
        {
            ResidentEntity data = residentApp.GetForm(keyValue);
            return Content(data.ToJson());
        }
        //详情页数据
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            ResidentEntity data = residentApp.GetForm(keyValue);
            if (null != data)
            {
                data.FaceData = string.Format("/{0}", data.FaceData);
            }
            return Content(data.ToJson());
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitForm(ResidentEntity residentEntity, string keyValue)
        {
            //只修改，不新增
            residentApp.SubmitForm(residentEntity, keyValue);
            return Success("操作成功。");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize(ignore:false)]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValue)
        {
            residentApp.Del(keyValue);
            return Success("删除成功。");
        }
        /// <summary>
        /// 导入居民信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadFile(HttpPostedFileBase file)
        {
            HttpPostedFileBase excelFile = Request.Files[0];
            Stream stream = excelFile.InputStream;
            string fileName = excelFile.FileName;
            //List<DataAccess.S_RfIdPackageInfor> l = new List<DataAccess.S_RfIdPackageInfor>();
            if (!string.IsNullOrEmpty(fileName) && (fileName.EndsWith(".xlsx") || fileName.EndsWith(".xls")))
            {
                string str = fileName.Contains(".xlsx") ? ".xlsx" : ".xls";
                ISheet sheet = null;
                IWorkbook workbook = null;
                if (str == ".xlsx")
                {
                    // 2007版本
                    workbook = new XSSFWorkbook(stream);
                }
                else if (str == ".xls")
                {
                    // 2003版本
                    workbook = new HSSFWorkbook(stream);
                }
                sheet = workbook.GetSheetAt(0);
                if (sheet != null)
                {
                    List<string> countList = new List<string>();
                    for (int i = 3; i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　
                        string IDNumber = row.GetCell(6) == null ? "" : row.GetCell(6).ToString().Trim();//证件号码
                        if (string.IsNullOrEmpty(IDNumber)) continue;
                        //以此证件号码去数据库检索，若存在则更新，不存在的话，直接插入一条新纪录
                        ResidentEntity selResident = residentApp.GetFormByIDNumber(IDNumber);
                        if (null != selResident)
                        {
                            selResident.RName = row.GetCell(1) == null ? "" : row.GetCell(1).ToString().Trim();//姓名
                            selResident.sex = row.GetCell(2) == null ? "" : row.GetCell(2).ToString().Trim();//性别
                            selResident.telephone = row.GetCell(3) == null ? "" : row.GetCell(3).ToString().Trim();//联系方式1
                            selResident.address = row.GetCell(4) == null ? "" : row.GetCell(4).ToString().Trim();//住址
                            //selResident.telephone2 = row.GetCell(5) == null ? "" : row.GetCell(5).ToString().Trim();//联系方式2
                            selResident.CardType = row.GetCell(5) == null ? "" : row.GetCell(5).ToString().Trim();//证件类型
                            residentApp.Update(selResident);
                        }
                        else
                        {
                            countList.Add(IDNumber);
                        }
                    }
                    if (countList.Count == 0)
                    {
                        return Json(new { success = "全部导入成功！" });
                    }
                    else
                    {
                        return Json(new { success = "部分导入成功！\r\n" + string.Format("未成功证件号码：\r\n{0}", string.Join(",\r\n",countList)) });
                    } 
                }
                else
                {
                    return Json(new { success = "无表单" });
                }
            }
            else
            {
                return Json(new { success = "该文件不是Excel" });
            }
        }
        /// <summary>
        /// Excel模板下载
        /// </summary>
        /// <returns></returns>
        public void Download_Excel(object sender, EventArgs e)
        {
            var path = Server.MapPath("~/ExcelModel/DiningInfoImportModelExcel.xls");      //模板所在路径和模板名
            var name = "DiningInfoImportModelExcel.xls";
            try
            {
                var file = new FileInfo(path);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name)); //头信息，指定默认文件名
                Response.AddHeader("Content-Length", file.Length.ToString());//显示下载进度
                Response.ContentType = "application/ms-excel";     // 指定返回的是一个不能被客户端读取的流，必须被下载
                Response.WriteFile(file.FullName);    // 把文件流发送到客户端
                Response.End();
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('错误:" + ex.Message + ",请尽快与管理员联系')</script>");
            }
        }
    }
}
